﻿using BW.WMS.CodeEnum;
using BW.WMS.Model;
using BW.WMS.StoreManagement_XKY.DTO.Input;
using BW.WMS.StoreManagement_XKY.DTO.Output;
using BW.WMS.XKY;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace BW.WMS.StoreManagement_XKY
{
    public class Dm_EncoderuleAppService : ApplicationService, IDm_EncoderuleAppService
    {
        private readonly IRepository<Dm_Encoderule, Guid> _repository;
        private readonly IRepository<EncoderuleInfo, Guid> _encoderuleInfo;
        private readonly IRepository<UserModel, Guid> _userRepository;
        public Dm_EncoderuleAppService(IRepository<Dm_Encoderule, Guid> repository, IRepository<EncoderuleInfo, Guid> encoderuleInfo, IRepository<UserModel, Guid> userRepository)
        {
            _repository = repository;
            _encoderuleInfo = encoderuleInfo;
            _userRepository = userRepository;
        }
        public async Task<ApiResult<int>> Add(Dm_EncoderuleInput input)
        {
            input.Id = Guid.NewGuid();
            input.Erid += input.Erprefix;
            if (input.Ertimerule == 1) { input.Erid += "YYYYMMDD"; }
            else if (input.Ertimerule == 2) { input.Erid += "YYYYMMDDHHmmss"; }
            else if (input.Ertimerule == 3) { input.Erid += "HHmmss"; }
            var i = 1;
            input.Erid += i.ToString().PadLeft(Convert.ToInt32(input.Ernum), '0');
            var data=ObjectMapper.Map<Dm_EncoderuleInput, Dm_Encoderule>(input);
            await _repository.InsertAsync(data);
            return new ApiResult<int>()
            {
                Code = ApiEnum.Success,
                Message = "添加成功",
                Data = 1
            };
        }

        public async Task<ApiResult<Dm_EncoderuleInput>> Get(Guid id)
        {
            var data=await _repository.FindAsync(id);
            return new ApiResult<Dm_EncoderuleInput>()
            {
                Code = ApiEnum.Success,
                Message = "查询成功",
                Data = ObjectMapper.Map<Dm_Encoderule, Dm_EncoderuleInput>(data)
            };
        }

        public async Task<ApiPaging<Dm_EncoderuleOutput>> GetList(int pageIndex, int pageSize, string? Erprefix, string? Formtypeid)
        {
            var pagedata=await _repository.GetQueryableAsync();
            if (!string.IsNullOrEmpty(Erprefix)) 
            {
                pagedata=pagedata.Where(x=>x.Erprefix.Contains(Erprefix));
            }
            if (!string.IsNullOrEmpty(Formtypeid) && Formtypeid !="undefined") 
            {
                pagedata=pagedata.Where(x=>x.Formtypeid==Formtypeid);
            }
            var data=ObjectMapper.Map<List<Dm_Encoderule>, List<Dm_EncoderuleOutput>>(pagedata.ToList());
            var userList = await _userRepository.GetListAsync();
            
            foreach (var item in data) 
            {
                // 假设 Dm_EncoderuleOutput 有 UserId，先拿到关联的 UserId
                var userId = item.CreatorId; // 需要确保 Dm_EncoderuleOutput 有 UserId 字段
                var user = userList.FirstOrDefault(u => u.Id == userId); // 根据 UserId 匹配 UserS
                if (user != null)
                {
                    item.UserName = user.UserName; // 填充 User 数据到 Output
                }

            }

            return new ApiPaging<Dm_EncoderuleOutput>()
            {
                
                TotalCount = pagedata.Count(),
                TotalPages = (int)Math.Ceiling(pagedata.Count()*1.0/pageSize),
                PageData =(data.OrderByDescending(a => a.CreationTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList())
            };
        }
        /// <summary>
        /// 开始编码
        /// </summary>
        /// <param name="Formtypeid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<string>> StartCode(string Formtypeid)
        {
            var data =await _repository.GetAsync(x => x.Formtypeid == Formtypeid);
            var a = await _encoderuleInfo.FirstOrDefaultAsync(x => x.Formname == data.Formtypeid);
            string code = "";
            code += data.Erprefix;
            if (data.Ertimerule == 1) { code += DateTime.Now.ToString("yyyyMMdd"); }
            else if (data.Ertimerule == 2) { code += DateTime.Now.ToString("yyyyMMddHHmmss"); }
            else if(data.Ertimerule == 3) { code += DateTime.Now.ToString("HHmmss");}
            // 2. 判断是否跨周期，决定是否重置序号（i）
            bool needReset = false;
            var now = DateTime.Now;
            if (a!=null)
            {
                switch (data.Ertype)
                {
                    case 0: // 每日自增
                        needReset = Convert.ToDateTime(a.LastModificationTime).Date == now.Date;
                        break;
                    case 1: // 每月自增（你代码里的场景）
                        needReset = Convert.ToDateTime(a.LastModificationTime).Month == now.Month
                                  || Convert.ToDateTime(a.LastModificationTime).Year == now.Year;
                        break;
                    case 2: // 每年自增
                        needReset = Convert.ToDateTime(a.LastModificationTime).Year == now.Year;
                        break;
                    default:
                        throw new ArgumentOutOfRangeException("无效的增长类型");
                }
            }
            // 3. 动态设置 i（CurrentNumber）
            
            int i;
            if (!needReset)
            {
                i = 1; // 跨周期，重置为 1
            }
            else
            {
                string encoded = a.Ercode.Trim();
                // 正则：匹配末尾的数字（\d+ 表示连续数字，$ 表示结尾）
                Match match = Regex.Match(encoded, @"\d+$");
                var lastNumberStr =match.Value;
                int last =Convert.ToInt32(lastNumberStr.Substring(lastNumberStr.Length -Convert.ToInt32(data.Ernum)));
                i = last+1;// 不跨周期，序号 +1
            }
            code += i.ToString().PadLeft(Convert.ToInt32(data.Ernum), '0');

            if (a == null)
            {
                EncoderuleInfo info = new EncoderuleInfo();
                info.Erid = data.Erid;
                info.Ername = data.Ername;
                info.Ercode = code;
                info.Formname = data.Formtypeid;
                info.LastModificationTime = DateTime.Now;
                await _encoderuleInfo.InsertAsync(info);
            }
            else
            {
                a.Erid = data.Id.ToString();
                a.Ername = data.Ername;
                a.Ercode = code;
                a.Formname = data.Formtypeid;
                a.LastModificationTime = DateTime.Now;
                await _encoderuleInfo.UpdateAsync(a);
            }
            return new ApiResult<string>()
            {
                Code=ApiEnum.Success,
                Data=code,
                Message="生成成功"
            };
        }

        public async Task<ApiResult<int>> Update(Dm_EncoderuleInput input)
        {
            input.Erid = "";
            input.Erid += input.Erprefix;
            if (input.Ertimerule == 1) { input.Erid += DateTime.Now.ToString("yyyyMMdd"); }
            else if (input.Ertimerule == 2) { input.Erid += DateTime.Now.ToString("yyyyMMddHHmmss"); }
            else if (input.Ertimerule == 3) { input.Erid += DateTime.Now.ToString("HHmmss"); }
            var i = 1;
            input.Erid += i.ToString().PadLeft(Convert.ToInt32(input.Ernum), '0');
            input.LastModificationTime = DateTime.Now;
            var a=await _repository.FindAsync(input.Id);
            ObjectMapper.Map(input,a);
            await _repository.UpdateAsync(a);
            return new ApiResult<int>()
            {
                Code = ApiEnum.Success,
                Message = "修改成功",
                Data = 1
            };
        }
    }
}
